Cache Policy
The cache policy enables you to cache the upstream response (content, status, and headers) and avoid subsequent calls to the backend.
This policy is based on a cache resource defined at the API level and allows the underlying cache system to follow the API lifecycle (stop / start). Cache resource is created automatically when you attach the cache policy rule to an API.
You can bypass cache by adding a cache=BY_PASS query parameter or by providing an X-Gravitee-Cache=BY_PASS HTTP header.
If you have a multi-node Gateway cluster, the API request will be cached for each node because the cache is JVM-centric.
Timing
| On Request | On Response |
|---|---|
| X |
Configuration
| Property | Required | Description | Type | Default |
|---|---|---|---|---|
cacheName | yes | The cache resource used to store the element. | string | |
key | no | The key used to store the element (supports EL). | string | |
timeToLiveSeconds | yes | Time to live of the element in cache. | integer | 600 (10 minutes) |
methods | no | The method to cache. | array of strings | [GET,OPTIONS,HEAD] |
responseCondition | no | Add an extra condition (with Expression Language) based on the response to activate cache. For example, use {#upstreamResponse.status == 200} to only cache 200 responses status. If a responseCondition is not specified, all 2xx responses are cached by default. | string | |
useResponseCacheHeaders | no | Time to live based on 'Cache-Control' and/or 'Expires' headers from backend response. | boolean | false |
scope | yes | Cached response can be set for a single consumer (application) or for all applications. Caution If you use an \"API\" scope, data will be shared between all consumers. | API/APPLICATION | APPLICATION |
Examples
Key based on the productId query parameter:
"key": "{#request.params['productId']}"
Key based on the api-key of the consumer:
"key": "{#request.headers['X-Gravitee-Api-Key']}"
Key based on an API’s property and a query parameter:
"key": "{#properties['siteID']}-{#request.params['productId']}"
Configuration example:
"cache": {
"cacheName": "policy-cache",
"key": "{#request.params['productId']}",
"timeToLiveSeconds": 600,
"useResponseCacheHeaders": false,
"scope": "APPLICATION",
"methods": ["POST"],
"responseCondition": "{#upstreamResponse.status == 201}"
}